import userAPI from '@/apis/user'
import storage from 'good-storage'
import regionAPI from '@/apis/region'

export default {
  getRoleInfo (instanceId) {
    const userInfo = storage.get('user_info')
    const userId = userInfo.userId
    return new Promise((resolve, reject) => {
      userAPI.queryUserRolesCurLevel({
        instanceId,
        userId: userId
      }).then(res => {
        if (res && res.data && res.data.code == '200') {
          let roles = res.data.data.filter(user => user.userId == userId)
          const countryFlag = '{$country$}'
          const coutryRole = roles.find(r => {
            if (r.areaLevel && r.areaLevel.indexOf(countryFlag) > -1) {
              return r
            } else if (r.instanceRoleCode && r.instanceRoleCode.indexOf(countryFlag) > -1) {
              return r
            }
          })

          const privinceFlag = '{$privince$}'
          const privinceRole = roles.find(r => {
            if (r.areaLevel && r.areaLevel.indexOf(privinceFlag) > -1) {
              return r
            } else if (r.instanceRoleCode && r.instanceRoleCode.indexOf(privinceFlag) > -1) {
              return r
            }
          })

          const cityRoleFlag = '{$city$}'
          const cityRole = roles.find(r => {
            if (r.areaLevel && r.areaLevel.indexOf(cityRoleFlag) > -1) {
              return r
            } else if (r.instanceRoleCode && r.instanceRoleCode.indexOf(cityRoleFlag) > -1) {
              return r
            }
          })

          const branchRoleFlag = '{$branch$}'
          const branchRole = roles.find(r => {
            if (r.areaLevel && r.areaLevel.indexOf(branchRoleFlag) > -1) {
              return r
            } else if (r.instanceRoleCode && r.instanceRoleCode.indexOf(branchRoleFlag) > -1) {
              return r
            }
          })

          const gridRoleFlag = '{$grid$}'
          const gridRole = roles.find(r => {
            if (r.areaLevel && r.areaLevel.indexOf(gridRoleFlag) > -1) {
              return r
            } else if (r.instanceRoleCode && r.instanceRoleCode.indexOf(gridRoleFlag) > -1) {
              return r
            }
          })

          const fieldRoleFlag = '{$field$}'
          const fieldRole = roles.find(r => {
            if (r.areaLevel && r.areaLevel.indexOf(fieldRoleFlag) > -1) {
              return r
            } else if (r.instanceRoleCode && r.instanceRoleCode.indexOf(fieldRoleFlag) > -1) {
              return r
            }
          })

          let role = coutryRole || privinceRole || cityRole || branchRole || gridRole || fieldRole || null

          if (!role) {
            role = roles[0]
          }

          if (location.href.indexOf('localhost') > -1) {
            // 设定可访问范围
            if (!role['targetId']) {
              role.targetId = 'SD.LA.0a'
            }
          }

          if (!role.clientId) {
            role.clientId = userInfo.tenants[0].clientId
          }

          if (window.current_user_id) {
            storage.set('role_info' + window.current_user_id, role)
          }

          storage.set('role_info', role)
          window._xvueStore.commit('setRoleInfo', role)
          window._adoPremise.user.roles = roles
          window._adoPremise.user.currentRole = role

          return resolve(true)
        }
        return reject(false)
      })
    })
  },
  getTenantTopRegion () {
    return new Promise((resolve, reject) => {
      const userInfo = storage.get('user_info')
      let currentTenant = ''
      if (userInfo.tenantId) {
        currentTenant = userInfo.tenants.find(t => t.tenantId == userInfo.tenantId)
      } else {
        currentTenant = userInfo.tenants.find(t => t.clientId == userInfo.currentClientId)
      }
      regionAPI.getTopRegion(currentTenant.tenantId).then((result) => {
        if (result && result.data && result.data.data && result.data.data.length) {
          storage.set('top_region', result.data.data[0].code)
          window._xvueStore.commit('Set_Top_Region', result.data.data[0].code)
          window._adoPremise.topRegion = result.data.data[0].code
          return resolve(true)
        }
      }).catch((err) => {
        console.error(err)
      })
    })
  },
  getUserRegions () {
    return new Promise((resolve, reject) => {
      let roleInfo = null
      if (window.current_user_id) {
        roleInfo = storage.get('role_info' + window.current_user_id)
      } else {
        roleInfo = storage.get('role_info')
      }

      let targetId = roleInfo.targetId

      let regons_123 = get123LevelRegions()
      let regons_4 = get4LevelRegions(targetId)

      Promise.all([regons_123, regons_4]).then(result => {
        let regions = []
        let arr4 = []
        let arr5 = []

        result.forEach(e => {
          if (e.type == '123level') regions = [...e.data]
          if (e.type == '4level') arr4 = [...e.data]
          if (e.type == '5level') arr5 = [...e.data]
        })

        let arr45 = [...arr4, ...arr5]

        arr45.forEach((e, i, s) => {
          let _region = regions.find(r => r.code == e.code)
          if (!_region) {
            regions.push(JSON.parse(JSON.stringify(s[i])))
          }
        })

        // 过滤后的数组
        let regionArr = []
        let topRegion = storage.get('top_region')
        if (targetId == topRegion || targetId == '') {
          regionArr = [...regions]
        } else {
          regions.forEach(e => {
            if (e.parentCode == targetId) regionArr.push(e)
          })
          handlDataByTargetId(targetId)
        }

        storage.set('all_regions', regionArr)
        window._xvueStore.commit('Get_Regions', regionArr)
        window._xvueStore.commit('Set_Login_Region', roleInfo.targetId)
        window._adoPremise.regions = regionArr
        window._adoPremise.loginRegion = roleInfo.targetId
        window._adoPremise.currentRegion = roleInfo.targetId

        resolve(true)

        function handlDataByTargetId (tId) {
          let curObj = regions.find(e => e.code == tId)

          if (curObj.parentCode) {
            regionArr.push(curObj)
            handlDataByTargetId(curObj.parentCode)
          } else {
            regionArr.push(curObj)
          }
        }
      })

      function get123LevelRegions () {
        let _topRegion = storage.get('top_region')
        let params = {
          'apiCode': 'getProAreaCountryList',
          'params': [{
            'code': 'grid_code',
            'value': _topRegion
          }]
        }
        return new Promise((resolve, reject) => {
          // 初始获取省市区3级区域
          regionAPI.getRegionsByApi(params).then((result) => {
            if (result.data && result.data.data && result.data.data.length) {
              resolve({
                data: result.data.data,
                type: '123level'
              })
            }
          }).catch((err) => {
            console.error(err)
          })
        })
      }

      function get4LevelRegions (code4) {
        return new Promise((resolve, reject) => {
          regionAPI.getCurrentRegionPrtChdRegs(code4).then((result) => {
            if (result && result.length) {
              resolve({
                data: result,
                type: '4level'
              })
            }
          }).catch((err) => {
            console.error(err)
            resolve({
              data: [],
              type: '4level'
            })
          })
        })
      }
    })
  },
  getUserPermissions (instanceId) {
    return new Promise((resolve, reject) => {
      userAPI.getUserPermission(instanceId).then(res => {
        if (res && res.data) {
          storage.set('user_permissions', res.data)
          window._xvueStore.commit('setPermissions', res.data)
          window._adoPremise.uc.permissionTags = res.data
          return resolve(true)
        }
      }).catch((err) => {
        console.error(err)
      })
    })
  }
}
